package de.szut.ita13sommerfeld.apacheanalyser.commander;

import java.io.File;

import de.szut.ita13sommerfeld.apacheanalyser.components.ApacheComponent;

public class ApacheCommander implements ApacheComponent {

	public static final int FLAG_FILE = 0x1;
	
	public static final int[] BITMASK_FLAGS = {0x2,0x4,0x8,0x10,0x20,0x40};
	public static final char[] FLAG_OPTIONS = {'S','u','m','r','s','d'};
	
	
	private String[] commands;
	private int flag;
	private File file;
	private File statistics;
	
	public ApacheCommander(String[] commands) {
		this.commands = commands;
		flag = 0;
	}
	
	public void parsingCommands()  {
		if(commands.length >= 1) {
			for(int i = 0; i < commands.length; i++) {
				String command = commands[i];
				if(command.endsWith(".log")) {
					file = new File(command);
					if(file.exists()) {
						flag += FLAG_FILE;
					}
				} else {
					boolean found = false;
					char currentChar;
					for(int j = 0; j < command.length() && !found; j++) {
						currentChar = command.charAt(j);
						if(currentChar == '-') {
							if(j + 1 < command.length()) {
								for(int k = 0; k < FLAG_OPTIONS.length && !found; k++) {
									if(command.charAt(j + 1) == FLAG_OPTIONS[k]) {
										if((flag & BITMASK_FLAGS[k]) != BITMASK_FLAGS[k]) {
											if(k != 0) {
												flag += BITMASK_FLAGS[k];
												found = true;
											} else {
												String path = command.substring(j + 2, command.length());
												if(path.endsWith(".properties") && path.substring(j + 2, path.indexOf(".properties")).length() > 0 || path.length() == 0) {
													statistics = new File(path);
													flag += BITMASK_FLAGS[0];
													found = true;
												}
											}
										}
									}
								}
								if(!found) 
									flag = 0;
							}
						}
					}
				}
			}
		}
	}
	
	public File[] getFiles() {
		File[] files = {file, statistics};
		return files;
	}
	
	public String[] getCommands() {
		return commands;
	}
	
	public int getFlag() {
		return flag;
	}
}
